/*
 Copyright (C) 2010 Chris Hawkins. All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
 
 * Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.
 
 * Neither the name of the author nor the names of its contributors may be used
 to endorse or promote products derived from this software without specific
 prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#import "ViewSetting.h"
#import "AppDelegate_Shared.h"

@implementation TASDViewSetting
@synthesize tvControllerDetail;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)                viewDidLoad {
    [super viewDidLoad];
    
    AppDelegate_Shared  *appDelegate = [[UIApplication sharedApplication] delegate];
    configManager = [[appDelegate configManager] retain];

    [[NSNotificationCenter defaultCenter] addObserver: self 
                                             selector: @selector(notificationConfigManager:)
                                                 name: [TASDConfigManager kNotification] 
                                               object: nil];
    [[self navigationItem] setTitle: @"Settings"];
}
- (void)                viewDidUnload {
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver: self];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}
- (void)                dealloc {
    [configManager release];
    [super dealloc];
}
#pragma mark -- ASDTConfigManager
- (NSObject<TASD_ConfigProvider>*) providerForRowAtIndexPath: (NSIndexPath*) indexPath_ {
    NSObject<TASD_ConfigProvider>* provider    = nil;
    if ( 0 == indexPath_.section ) {
        switch ( indexPath_.row ) {
            case  0: provider = [configManager providerAwsEndpoint];        break;
            case  1: provider = [configManager providerAwsSignature];       break;
            default:                                                        break;
        }
    }
    if ( 1 == indexPath_.section ) {
        switch ( indexPath_.row ) {
            case  0: provider = [configManager providerDomain];             break;
            case  1: provider = [configManager providerSelect];             break;
            case  2: provider = [configManager providerDomainItem];         break;
            case  3: provider = [configManager providerDomainItemCount];    break;
            case  4: provider = [configManager providerDomainAttribute];    break;
            default:                                                        break;
        }
    }
    return provider;
}
- (void)                notificationConfigManager: (NSNotification*) notification_ {
    [[self tableView] reloadData];    
}
#pragma mark -- UITableViewDataSource
- (NSInteger)           numberOfSectionsInTableView: (UITableView*) tableView_ {
    return 2;
}
- (UITableViewCell*)    tableView: (UITableView*) tableView_ cellForRowAtIndexPath: (NSIndexPath*) indexPath_ {
    static NSString    *kCellIdentifier = @"SettingsMasterCell";
    UITableViewCell*                cell         = nil;
    NSObject<TASD_ConfigProvider>*  cellProvider = [[self providerForRowAtIndexPath:  indexPath_] retain];
    if ( cellProvider != nil ) {
        cell = [tableView_ dequeueReusableCellWithIdentifier: kCellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kCellIdentifier] autorelease];
            cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
        }
        [cellProvider populateMasterCell: cell key: [configManager valueKeyForProvider: cellProvider]];
    }
    [cellProvider release];
    return cell;
}
- (NSInteger)           tableView: (UITableView*) tableView_ numberOfRowsInSection: (NSInteger) section_ {
    return ( section_ == 0 ? 2 :
           ( section_ == 1 ? 5 : 0 ));
}
- (NSString*)           tableView: (UITableView *)tableView_ titleForHeaderInSection: (NSInteger) section_ {
    return ( section_ == 0 ? @"AWS Connection" : 
           ( section_ == 1 ? @"Test Data"      :@"Invalid" ));
}
#pragma mark -- UITableViewDelegate
- (void)        tableView: (UITableView*) tableView accessoryButtonTappedForRowWithIndexPath: (NSIndexPath*) indexPath_ {
    NSObject<TASD_ConfigProvider>*  cellProvider = [[self providerForRowAtIndexPath:  indexPath_] retain];
    if ( cellProvider != nil ) {
        [tvControllerDetail setProvider: cellProvider sink: configManager];
        [self.navigationController pushViewController: tvControllerDetail animated: YES];            
    }
    [cellProvider release];
}
@end

@implementation TASDViewSettingDetail 
- (void)                viewDidLoad {
    [super viewDidLoad];
}
#pragma mark -- Configuration 
- (void)                setValueKeys: (NSArray*) value_ {
    if ( ![valueKeys isEqual: value_] ) {
        [valueKeys release];
        valueKeys = [value_ retain];
    }
}
- (void)                setProvider: (NSObject<TASD_ConfigProvider>*) provider_ sink: (NSObject<TASD_ConfigSink>*) configSink_ {
    BOOL valid = ( provider_ != nil && configSink_ != nil );
    if ( valid ) {
        [provider_   retain];
        [configSink_ retain];
    }
    [configProvider release];
    [configSink     release];
    if ( valid ) {
        configProvider  = provider_;
        configSink      = configSink_;
        NSArray *keys   = [[[configProvider choices] allKeys] retain];
        [self setValueKeys:  [keys sortedArrayUsingSelector: @selector( caseInsensitiveCompare: )]];
        initialSelectionIndex = [valueKeys indexOfObject: [configSink valueKeyForProvider: configProvider]];
        [[self navigationItem] setTitle: [configProvider promptTitle]];
        [keys release];
    } else {
        configProvider  = nil;
        configSink      = nil;
        [self setValueKeys:  nil];
    }
    currentSelectionIndex = initialSelectionIndex;
    [[super tableView] reloadData];
}
#pragma mark -- NSObject standard
- (void)                dealloc {
    [configProvider release];
    [configSink     release];
    [self setValueKeys:    nil];
    [super dealloc];
}
#pragma mark -- UITableViewDataSource
- (NSInteger)           numberOfSectionsInTableView: (UITableView*) tableView_ {
    return 1;
}
- (UITableViewCell*)    tableView: (UITableView*) tableView_ cellForRowAtIndexPath: (NSIndexPath*) indexPath_ {
    static NSString    *kCellIdentifier = @"SettingsDetailCell";
    UITableViewCell    *cell            = nil;
    cell = [tableView_ dequeueReusableCellWithIdentifier: kCellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kCellIdentifier] autorelease];
    }
    NSString    *key   = [valueKeys objectAtIndex: indexPath_.row];
    [configProvider populateDetailCell: cell key: key];
    cell.accessoryType = ( currentSelectionIndex == indexPath_.row ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone );
    return cell;
}
- (NSInteger)           tableView: (UITableView*) tableView_ numberOfRowsInSection: (NSInteger) section_ {
    return [valueKeys count];
}
#pragma mark -- UITableViewDelegate
- (void)                tableView: (UITableView*) tableView_ didSelectRowAtIndexPath: (NSIndexPath*) indexPath_ {
    if ( currentSelectionIndex != indexPath_.row ) {
        NSIndexPath*     path = [NSIndexPath indexPathForRow: currentSelectionIndex inSection: indexPath_.section];
        UITableViewCell* cell = [tableView_ cellForRowAtIndexPath: path];
        cell.accessoryType = UITableViewCellAccessoryNone;
        currentSelectionIndex = indexPath_.row;
        cell = [tableView_ cellForRowAtIndexPath: indexPath_];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        
        [configSink setValueKey: [valueKeys objectAtIndex: currentSelectionIndex] forProvider: configProvider];
    }
}
@end

